package com.lingjtx.common.thread.mq;

import com.alibaba.fastjson2.JSONReader;

import java.util.List;

public class SafeAutoTypeHandler implements JSONReader.AutoTypeBeforeHandler {

    private final List<String> whitelist;

    public SafeAutoTypeHandler(List<String> whitelist) {
        this.whitelist = whitelist;
    }

    @Override
    public Class<?> apply(String typeName, Class<?> expectClass, long features) {
        for (String prefix : whitelist) {
            if (typeName != null && typeName.startsWith(prefix)) {
                try {
                    return Class.forName(typeName);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException("Cannot load class: " + typeName, e);
                }
            }
        }
        throw new SecurityException("AutoType is not allowed for class: " + typeName);
    }
}
